/**
 * Copyright (C) Skywares Information Technology, LTD. 
 * All Rights Reserved.
 *
 * DataInit.java created on 2020年2月7日 上午10:50:00 by Lyon Lu 
 */
package com.mvc.server.miaosha.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.mvc.server.component.RedisService;
import com.mvc.server.miaosha.redis.GoodsKey;
import com.mvc.server.miaosha.service.GoodsService;
import com.mvc.server.miaosha.vo.GoodsVo;

/**
 * <pre>
 * Description:
 * 
 * @author Lyon Lu
 * @date 2020年2月7日 上午10:50:00
 *
 * </pre>
 */
@Component
public class DataInit implements InitializingBean{
	
	@Resource
	private GoodsService goodsService;

	@Resource
	private RedisService redisService;
	
	// 用于保存秒杀货品初始化数量
	private static Map<Long, Integer> miaoshaStockMap =  new HashMap<Long, Integer>();
	
	@Override
	public void afterPropertiesSet() throws Exception {
		// 初始化秒杀货品库存
		initMiaoshaGoodsStockCache();
	}

	/**
	 * Description:
	 * 		method description here
	 * @param 
	 * @return void      
	 * @throws                                 
	 */
	private void initMiaoshaGoodsStockCache() {
		List<GoodsVo> goodsVos = goodsService.listGoodsVo();
		if (Objects.isNull(goodsVos) || goodsVos.size() == 0) {
			return;
		}
		
		for(GoodsVo goodsVo : goodsVos) {
			redisService.set(GoodsKey.getMiaoshaGoodsStock, String.valueOf(goodsVo.getId()), goodsVo.getStockCount());
			miaoshaStockMap.put(goodsVo.getId(), goodsVo.getStockCount());
		}
	}
	
	/**
	 * Description:
	 * 		获取初始的商品秒杀数量
	 * @param @param goodsId
	 * @return int      
	 * @throws
	 */
	public static int getGoodsStockOriginal(long goodsId) {
		Integer stock = miaoshaStockMap.get(goodsId);
		if(stock == null) {
			return 0;
		}
		return stock;
	}
}
